package com.junyi;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * 管理类，提供统一的参数验签
 * @time: 2021年11月24日 11:18
 * @author: junyi Xu
 */
@Component
public class NotifyServiceManagement implements ApplicationContextAware {

    private ApplicationContext applicationContext;
    public static Map<String, INotifyService> serviceMap = new ConcurrentHashMap<>();


    @PostConstruct
    public void init() {
        Map<String, INotifyService> classMap = applicationContext.getBeansOfType(INotifyService.class);
        if (CollectionUtils.isEmpty(classMap)) {
            return;
        }

        serviceMap = classMap.values().stream().collect(Collectors.toMap(INotifyService::handleType, t -> t));
    }


    public Integer handle(String request) {
        // 请求的通用处理逻辑，包括参数验证、合法性验证等，避免第三方恶意调用接口

        String type = "";       // 消息类型，从request中解析
        INotifyService iNotifyService = serviceMap.get(type);
        Integer result = iNotifyService.handle(request);
        return result;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
